﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Workflows.Components.Reports
{
	/// <summary>
	/// 
	/// </summary>
	public partial class FieldTransformCodeEditor : Form
	{
		/// <summary>
		/// 
		/// </summary>
		/// <param name="code"></param>
		public delegate void OnCodeUpdated(string code);

		public event OnCodeUpdated CodeUpdated;
		private readonly Dictionary<string, Type> methodArgs;
		private readonly string methodBody;

		/// <summary>
		/// 
		/// </summary>
		/// <param name="args"></param>
		/// <param name="body"></param>
		public FieldTransformCodeEditor(Dictionary<string,Type> args, string body)
		{
			InitializeComponent();
			this.methodArgs = args;
			this.methodBody = body;
		}

		private void FieldTransformCodeEditor_Load(object sender, EventArgs e)
		{
			StringBuilder buffer=new StringBuilder();
			buffer.Append("public string Transform(");
			string signature = string.Empty;
			if (this.methodArgs != null && this.methodArgs.Count > 0)
			{
				foreach (string argName in this.methodArgs.Keys)
				{
					if (signature.Length > 0)
						signature += ", ";
					signature += this.methodArgs[argName].ToString() + " " + argName;
				}
			}
			buffer.Append(signature);
			buffer.Append(") {");
			this.txt_MethodSig.Text = buffer.ToString();

			if(!string.IsNullOrEmpty(this.methodBody))
				this.rt_Code.Text = this.methodBody;
			else
				this.rt_Code.Text = string.Empty;
		}

		private void btn_OK_Click(object sender, EventArgs e)
		{
			if (this.CodeUpdated != null)
				this.CodeUpdated(this.rt_Code.Text);
			this.Close();
		}

		private void btn_Cancel_Click(object sender, EventArgs e)
		{
			this.Close();
		}
	}
}
